module vlib.ev.fcgi.Proxy;

import vlib.Types;

private {
	extern(Windows) {
		int bind(int , void*, int);
	}
}

struct vFcgi {
	alias typeof(*this) This ;
	alias typeof(this) pThis ;
	
	Berkeley		_soc ;
	int			_soc_fd ;
	vAddr4		_addr ;
	ev_io		read_watcher ;
	
	void Init(){
		_soc.open(AddressFamily.INET, SocketType.STREAM, ProtocolType.TCP) ;
		_soc.blocking( false ) ;
		read_watcher.data	= this ;
		_soc_fd = osf_open(cast(void*) _soc.handle);
		ev_io_init(&read_watcher, &On_Read , _soc_fd, EV_READ);
		assert( read_watcher.fd > 0);
		ev_io_start( vLib.loop, &read_watcher );
		_addr._family      = AddressFamily.INET ;  

		_addr._port	= vlib.util.Byte.htons( _G.fcgi_port ) ;	
		ubyte[4] ipv;
		vDns.isIp(  _G.fcgi_ip, ipv);
		tango.stdc.string.memcpy(&_addr._ip[0], &ipv[0], ipv.length );
		
		int	ret	= bind(_soc.handle, &_addr, _addr.sizeof) ;
		if( ret is -1 ) {
			lg("bind {}:{} error",  _G.fcgi_ip,  _G.fcgi_port );
			vLib.Exit(2);
		}
		_soc.listen(32);
	}
	
	
	static extern(C) void On_Read(ev_loop_t* loop, ev_io* w, int ev) {
		assert(loop is vLib.loop) ;
		assert(w !is null) ;
		pThis _this	= cast(pThis) w.data ;
		assert(_this !is null) ;
		vFcgReq.accept(_this._soc);
	}
	

}